from beagleclientpylons.lib.base import *
from beagleclientpylons.model.result import *
import mimetypes
import gnome.ui
import gtk
import urllib
import time
import datetime
import os



class IndexController(BaseController):
	
	def __init__(self):
		BaseController.__init__(self)
	
	def advanced(self):
		return render("/advanced.mako")
	
	def beagle(self):
		c.beagle = Beagle()
		return render("/beagle.mako")
	
    
	def detail(self):
		index = int(request.params.get('index'))
		c.hit = session['pager'].element_at(index)
		return render("/detail.mako")

	def tag(self):
		url = request.params.get('url', '')
		tag = [request.params.get('tag', '')]
		if tag != ['']:
			session['pager'].tagByUrl(url, tag)
			return "Tag Added!"
		else:
			return "Please enter a tag"

	def find(self):
		start_end = [None, None]
		if session.has_key('range'):
			range = session['range']
			start_end = self._start_end_from_range(range)	
		q = Query(request.params['query'], start_end[0], start_end[1])
		q.execute();
		p = Pager(10, q.get_hits())
		session['pager'] = p
		session['query'] = q
		session.save()
		return render("/result.mako")
	
	def _start_end_from_range(self, range):
		if not range in ['d', 'w', 'm', 'm2', 'm3', 'm6', 'y']:
			return [None, None]
		end = datetime.datetime.now()
		if range == 'd':	
			start = end - datetime.timedelta(days=1)
		elif range == 'w':
			start = end - datetime.timedelta(weeks=1)
		elif range == 'm':
			start = end - datetime.timedelta(weeks=4)
		elif range == 'm2':
			start = end - datetime.timedelta(weeks=8)
		elif range == 'm3':
			start = end - datetime.timedelta(weeks=12)
		elif range == 'm6':
			start = end - datetime.timedelta(weeks=24)
		else:
			start = end - datetime.timedelta(weeks=52)
		
		end = (int) (time.mktime(end.timetuple()))
		start = (int) (time.mktime(start.timetuple()))
		return [start, end]
    
	def next(self):
		session['pager'].next()
		session.save()
		return render("/result.mako")
    
    
	def prev(self):
		session['pager'].prev()
		session.save()
		return render("/result.mako")
    
    
	def index(self):
		c.beagle = Beagle()
		return render('/index.mako')
	
	def save_prefs(self):
		session['range'] = request.params.get('range', '')
		session['openwith'] = request.params.get('openwith', '')
		session.save()
		return "preferences noted"
    
	def open(self):
		uri = urllib.unquote(request.params.get('uri', ''))
		index = int(request.params.get('index'))
		hit = session['pager'].element_at(index)
		mimes = hit.get_properties('beagle:MimeType')
		if mimes is not None:
			mime = mimes[0]
		else:
			mime = mimetypes.guess_type(uri)[0]
		if not mime:
			mime = 'application/unknown'
		response.content_type__set(mime)
		f = urllib.urlopen(uri, proxies=None)
		def open_pause():
			segment = f.read(128)
			while segment != '':
				yield segment
				segment = f.read(128)
			f.close()
		return open_pause()
			
	def open_here(self):
		uri = urllib.unquote(request.params.get('uri', ''))
		APP = "gnome-open"
		os.spawnlp(os.P_NOWAIT, APP, APP, uri)
		
        
	def icon(self):
		iconTheme = gtk.icon_theme_get_default()
		iconFactory = gnome.ui.ThumbnailFactory(gnome.ui.THUMBNAIL_SIZE_NORMAL)
		uri = request.params.get('uri', '')
		result, flags = gnome.ui.icon_lookup(iconTheme, iconFactory, uri)
		info = iconTheme.lookup_icon(result, 32, gtk.ICON_LOOKUP_NO_SVG)
		if info is None:
			abort(404)
		else:
			icon_name = info.get_filename()
		
		index = int(request.params.get('index'))
		hit = session['pager'].element_at(index)
		mimes = hit.get_properties('beagle:MimeType')
		if mimes is not None:
			mime = mimes[0]
		else:
			mime = mimetypes.guess_type(uri)[0]
		
		if not mime:
			mime = 'application/unknown'
		response.content_type__set(mime)
		f = open(icon_name, "rb", 0)
		def open_pause():
			segment = f.read(128)
			while segment != '':
				yield segment
				segment = f.read(128)
			f.close()
		return open_pause()

     	
     
     
     

   